<?php
namespace App\Http\Questionnaire\Controllers;

use Illuminate\Http\Request;
use App\Http\Admin\Controllers\Controller as Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use App\User;
use App\Permission;
use App\Http\Authentication\UserAuthentication;

class UserController  extends Controller
{

    public function add_user(Request $request){
        $data = $request->only("phone","password","code");
        if(!array_key_exists("phone",$data)||!preg_match('/^1[34578]{1}\d{9}$/',$data['phone']))  return ThrowApiExc('32036');
        if(!array_key_exists("password",$data)||!preg_match('/^[0-9a-zA-Z]{2,30}$/u',$data['password'])) return ThrowApiExc('32037');

        //手机验证

        if(!Redis::get("phone_time:".$data['phone'])) return ThrowApiExc('32041');
        if(Redis::get("phone_time:".$data['phone'])!=$data['code']) return ThrowApiExc('32039');

        $user = User::where('phone', '=', $data['phone'])->first();
        if($user){
            return ThrowApiExc('103');
        }
        unset($data['code']);
        //[18] 用户角色
        $roles= [18];
        $data['password']=Hash::make($data['password']);
        $data['type']=2;
        $user= User::create($data);
        $user = User::where('phone', '=', $data['phone'])->first();

        $token = sha1(microtime().$user['phone'].$data['phone'].env('APP_KEY'));

        $ttl = 7 * 86400;  //过期时间 N *  天
        Redis::setex("code:".$token,$ttl,$user['id']);

        //
        $user ->attachRoles($roles);

        return [
            'status_code'      => 200,
            'message'     =>  '添加成功',
            'data' => [
                'token'=>$token,
                'expires_in'=>$ttl
            ]
        ];

    }

    public function update_user_name(Request $request){
        $data=$request->only("name","sex");
        if(!array_key_exists("name",$data)||!preg_match('/^[\w\x{4e00}-\x{9fa5}]{2,10}$/u',$data['name']))  return ThrowApiExc('31001');
        if(!array_key_exists("sex",$data)||!preg_match('/^[\d]{1}$/u',$data['sex']))  return ThrowApiExc('32043');
        $token = getToken($request);
        $uid =Redis::get("code:".$token);

        $user = User::where('id', '=', $uid)->first();
        $user->update($data);
        return [
            'status_code'      => 200,
            'message'     =>  '修改成功',
            'data' => 1
        ];

    }

    public function update_user_email(Request $request){
        $data = $request->only("email","code");
        $token = getToken($request);
        $uid =Redis::get("code:".$token);

        //邮箱验证
        if(!array_key_exists("email",$data)||!preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/',$data['email']))  return ThrowApiExc('32036');
        if(!Redis::get("email_time:".$data['email'])) return ThrowApiExc('32046');
        if(Redis::get("email_time:".$data['email'])!=$data['code']) return ThrowApiExc('32039');
        if(DB::table("users")->where("email",$data['email'])->first()) return ThrowApiExc('32045');
        $user = User::where('id', '=', $uid)->first();


        DB::table("users")->where("id",$uid)->update(['email'=>$data['email']]);
        return [
            'status_code'      => 200,
            'message'     =>  '修改成功',
            'data' => 1
        ];
    }


    public function update_password_email(Request $request){
        $token = getToken($request);
        $uid =Redis::get("code:".$token);

        $data = $request->only("password","email","code");
        //邮箱验证
        if(!array_key_exists("email",$data)||!preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/',$data['email']))  return ThrowApiExc('32036');
        if(!Redis::get("email_time:".$data['email'])) return ThrowApiExc('32041');
        if(Redis::get("email_time:".$data['email'])!=$data['code']) return ThrowApiExc('32039');

        $user = User::where('id', '=', $uid)->first();
        if(!Hash::check($data['password'],$user['password'])) return ThrowApiExc('102');
        $data['password']=Hash::make($data['password']); 
        $user->update(['password'=>$data['password']]);
        return [
            'status_code'      => 200,
            'message'     =>  '修改成功',
            'data' => 1
        ];
    }



    public function send_email(Request $request){
        $data = $request->only("email");
        if(!preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/',$data['email'])) return ThrowApiExc('32046');
        $token = getToken($request);
        $uid =Redis::get("code:".$token);
        $email = $data['email'];
        if(Redis::get("email_cd:".$email)) return ThrowApiExc('32042');
        $code = rand(100000,999999);
        $ttl = 10*60;  //过期时间 N 分钟
        Redis::setex("email_time:".$email ,$ttl,$code);
        Redis::setex("email_cd:".$email ,60,$code);
        $message = $code;

        $to = $data['email'];
        $content ="蜗牛家事";
//            $subject = '邮件名称';
        Mail::send(
            'email',
            ['content' => $message],
            function ($message) use($to, $content) {
                $message->to($to)->su温压弹bject($content);
            }
        );
        return [
            'status_code'      => 200,
            'message'     =>  '请求成功',
            'data' => "发送成功"
        ];

    }

    public function front_login(Request $request){
        $data=$request->only('phone','password');
        if(!array_key_exists("phone",$data)||!preg_match('/^1[34578]{1}\d{9}$/',$data['phone']))  return ThrowApiExc('32036');
        // if(!array_key_exists("code_key",$data)||!preg_match('/[\s\S]{1,400}/',$data['code_key']))  return ThrowApiExc('32036');

        // if (!captcha_api_check($data['code'], $data['code_key'])){

        //     return ThrowApiExc('100');
        // }



        $user=DB::table('users')->where('phone',$data['phone'])->first();

        if(!$user) return ThrowApiExc('101');

        if(!Hash::check($data['password'],$user['password'])) return ThrowApiExc('102');


        $token = sha1(microtime().$user['phone'].$data['phone'].env('APP_KEY'));

        $ttl = 7 * 86400;  //过期时间 N *  天
        Redis::setex("code:".$token,$ttl,$user['id']);

        Redis::del($request->verfiy_uuid); //删除验证码


        return [
            'status_code'      => 200,
            'message'     =>  '请求成功',
            'data' => [
                'token'=>$token,
                'expires_in'=>$ttl
            ]
        ];

    }



    public function update_password_phone(Request $request){


        $data = $request->only("password","phone");
        //手机验证
        if(!array_key_exists("phone",$data)||!preg_match('/^1[34578]{1}\d{9}$/',$data['phone']))  return ThrowApiExc('32036');

        if(!Redis::get("phone_code_3:".$data['phone'])||Redis::get("phone_code_3:".$data['phone'])!=2){
            return ThrowApiExc('32048');
        }

        $user = User::where("phone",$data['phone'])->first();
        $data['password']=Hash::make($data['password']);

        DB::table("users")->where("phone",$data['phone'])->update(['password'=>$data['password']]);
        return [
            'status_code'      => 200,
            'message'     =>  '修改成功',
            'data' => 1
        ];
    }

    public function update_password_phone2(Request $request){


        $data = $request->only("password","phone");
        //手机验证
        if(!array_key_exists("phone",$data)||!preg_match('/^1[34578]{1}\d{9}$/',$data['phone']))  return ThrowApiExc('32036');

        if(!Redis::get("phone_code_4:".$data['phone'])||Redis::get("phone_code_4:".$data['phone'])!=2){
            return ThrowApiExc('32048');
        }

        $user = User::where("phone",$data['phone'])->first();
        $data['password']=Hash::make($data['password']);

        DB::table("users")->where("phone",$data['phone'])->update(['password'=>$data['password']]);
        return [
            'status_code'      => 200,
            'message'     =>  '修改成功',
            'data' => 1
        ];
    }

    public function update_phone(Request $request){
        $token = getToken($request);
        $uid =Redis::get("code:".$token);

        $data = $request->only("old_phone","phone","code");
        //手机验证
        if(!Redis::get("phone_code_2:".$data['old_phone'])||Redis::get("phone_code_2:".$data['old_phone'])!=2){
            return ThrowApiExc('32048');
        }
         //手机验证
        if(!array_key_exists("phone",$data)||!preg_match('/^1[34578]{1}\d{9}$/',$data['phone']))  return ThrowApiExc('32036');
        if(!Redis::get("phone_time:".$data['phone'])) return ThrowApiExc('32041');
        if(Redis::get("phone_time:".$data['phone'])!=$data['code']) return ThrowApiExc('32039');
        $user = User::where('id', '=', $uid)->first();
        $user->update($data);
        return [
            'status_code'      => 200,
            'message'     =>  '修改成功',
            'data' => 1
        ];
    }

    /**
     * 手机验证码
     * param $phone 手机号
     * param $type 1注册2修改手机号3修改密码 5登陆
     */
    public function phone_code(Request $request){
        $token = getToken($request);
        $uid =Redis::get("code:".$token);
        $data = $request->only("phone","type");
        if(!array_key_exists("phone",$data)||!preg_match('/^1[34578]{1}\d{9}$/',$data['phone']))  return ThrowApiExc('32036');
        //type不存在 格式为非字数字 长度不等于1
        if(!array_key_exists('type',$data)||!preg_match('/^[\d]{1,2}$/u',$data['type'])) return ThrowApiExc('32002');

        $type_data = [
            5=>"SMS_195586224",
            4=>"SMS_193515326",
            3=>"SMS_191151460",
            2=>"SMS_191195902",
            1=>"SMS_191190876",
        ];

        if($data['type']==3||$data['type']==1||$data['type']==5){
            $res2 = DB::table("users")->where("phone",$data['phone'])->first();
            switch($data['type']){
                case 3:
                    if(!$res2) return ThrowApiExc('32047');
                break;
                case 5:
                    if(!$res2) return ThrowApiExc('32047');
                break;
                case 1:
                    if($res2) return ThrowApiExc('103');
                break;
            }
           
        }

        $res = aliyun_sms($data['phone'],$type_data[$data['type']],rand(100000,999999));

        Redis::setex("phone_code_{$data['type']}:".$data['phone'],60*10,1);//1未验证 2已验证
        
        if($res){
            return [
                'status_code'      => 200,
                'message'     =>  '提交成功',
                'data' => 1
            ];
        }else{
            return [
                'status_code'      => 200,
                'message'     =>  '提交失败',
                'data' => 0
            ];
        }
    }

    public function phone_code_v(Request $request){
        $data= $request->only("phone","code","type");
        if(!array_key_exists("phone",$data)||!preg_match('/^1[34578]{1}\d{9}$/',$data['phone']))  return ThrowApiExc('32036');
        //手机验证

        if(!Redis::get("phone_time:".$data['phone'])) return ThrowApiExc('32041');
        if(Redis::get("phone_time:".$data['phone'])!=$data['code']) return ThrowApiExc('32039');

        if(!Redis::get("phone_code_{$data['type']}:".$data['phone'])) return ThrowApiExc('32049');
        if(Redis::get("phone_code_{$data['type']}:".$data['phone'])!=1) return ThrowApiExc('32050');
        Redis::setex("phone_code_{$data['type']}:".$data['phone'],60*10,2);//1未验证 2已验证

        return [
            'status_code'      => 200,
            'message'     =>  '验证成功',
            'data' => 1
        ];
    }

    public function upload_user_photo(Request $request){
        $token = getToken($request);
        $uid =Redis::get("code:".$token);

        $data = $request->only("files");

        if(!array_key_exists('files',$data)) return ThrowApiExc('32033');
        if(array_key_exists('files',$data)){    //判断是否有图片
            $imgName = "problem/".date("Y",time())."/".date("m",time())."/".date("d",time())."/".date("YmdHis", time()) . rand(1000, 9999) . rand(1000, 9999) . "." . $data['files']->getClientOriginalExtension();  //文件重命名
            $imgurl= Oss($data['files'], $imgName)['info']['url'];
            $data['photo'] = $imgurl;
        }
        unset($data['files']);
        $user = User::where('id', '=', $uid)->first();
        $user->update($data);
        return [
            'status_code'      => 200,
            'message'     =>  '修改成功',
            'data' => $imgurl
        ];
    }

    public function phone_v(Request $request){
        $data=$request->only("phone");
        $res = DB::table("users")->where("phone",$data['phone'])->first();

        if($res){
            return [
                'status_code'      => 200,
                'message'     =>  '验证成功',
                'data' => 1
            ];
        }
    }


    public function code_login_phone(Request $request){
        $data = $request->only("phone","code");
        if(!array_key_exists("phone",$data)||!preg_match('/^1[34578]{1}\d{9}$/',$data['phone']))  return ThrowApiExc('32036');
        if(!array_key_exists("code",$data)||!preg_match('/[0-9]{6}$/',$data['code']))  return ThrowApiExc('32051');

        if(!Redis::get("phone_code_5:".$data['phone'])||Redis::get("phone_code_5:".$data['phone'])!=1){
            return ThrowApiExc('32048');
        }
        if(Redis::get("phone_time:".$data['phone'])!=$data['code']) return ThrowApiExc('32039');
        $user = DB::table("users")->where("phone",$data['phone'])->first();
        DB::table("users")->where("id",$user['id'])->update(['last_login'=>date("Y-m-d H:i:s",time())]);
        if($user){
            $token  =   sha1(microtime().$user['name'].$data['code'].env('APP_KEY'));

            $ttl = 3 * 86400;  //过期时间 N *  天
            Redis::setex("code:".$token,$ttl,$user['id']);

            return [
                        'status_code'      => 200,
                        'message'     =>  '请求成功',
                        'data' => [
                            'token'=>$token,
                            'expires_in'=>$ttl
                        ]
                    ];

        }else{
            ThrowApiExc('32047');
        }

    }


    // public function select_user_log($uid){

    //     $data = DB::table("user_log")->where("id",$uid)->paginate(20);
    //     if($data){
    //         return [
    //             'status_code'      => 200,
    //             'message'     =>  '搜索成功',
    //             'data' => $data
    //         ];
    //     }else{
    //         return [
    //             'status_code'      => 200,
    //             'message'     =>  '搜索失败',
    //             'data' => $data
    //         ];
    //     }
    // }

    public function  add_user_news_log(Request $request){
        //type 1搜索 2查询栏目 3查看文章
        $data = $request->only("key_word","newsId","type");

        // if(!array_key_exists("newsId",$data)||!preg_match('/[0-9]{1,10}$/',$data['newsId']))  return ThrowApiExc('32052');

        if(!array_key_exists("type",$data)||!preg_match('/[0-9]{1}$/',$data['type']))  return ThrowApiExc('20008');

        $data['created_time']=date("Y-m-d H:i:s",time());
        $token = getToken($request);
        $data['userId'] =Redis::get("code:".$token);
        $res = DB::table("user_news_log")->insertGetId($data);

        if($res){
            return [
                'status_code'      => 200,
                'message'     =>  '添加成功',
                'data' => $res
            ];
        }else{
            return [
                'status_code'      => 200,
                'message'     =>  '添加失败',
                'data' => $res
            ];
        }
    }

    public function stop_user_news_log($unlId){
        $res = DB::table("user_news_log")->where("id",$unlId)->update(['stop_time'=>date("Y-m-d H:i:s",time())]);
        if($res){
            return [
                'status_code'      => 200,
                'message'     =>  '结束成功',
                'data' => $res
            ];
        }else{
            return [
                'status_code'      => 200,
                'message'     =>  '结束失败',
                'data' => $res
            ];
        }
    }

    public function add_questionnaire_log($quid){
        $res = DB::table("user_questionnaire_log")->insertGetId(['quid'=>$quid,"created_time"=>date("Y-m-d H:i:s",time())]);
        if($res){
            return [
                'status_code'      => 200,
                'message'     =>  '添加成功',
                'data' => $res
            ];
        }else{
            return [
                'status_code'      => 200,
                'message'     =>  '添加失败',
                'data' => $res
            ];
        }
    }
    public function stop_questionnaire_log($uqlId){

        $res = DB::table("user_questionnaire_log")->where("id",$uqlId)->update(["stop_time"=>date("Y-m-d H:i:s",time())]);
        if($res){
            return [
                'status_code'      => 200,
                'message'     =>  '添加成功',
                'data' => $res
            ];
        }else{
            return [
                'status_code'      => 200,
                'message'     =>  '添加失败',
                'data' => $res
            ];
        }
    }

    public function select_user_news_log($uid){
        $data = DB::table("user_news_log as unl")
        ->leftJoin("news as n","n.id","=","unl.newsId")
        ->leftJoin("action as a","n.faid","=","a.id")
        ->where("unl.userId",$uid)
        ->select("unl.*","n.title as newsTitle","n.source","a.title as actionTitle")
        ->get();

        if($data){
            return [
                'status_code'      => 200,
                'message'     =>  '查询成功',
                'data' => $data
            ];
        }else{
            return [
                'status_code'      => 200,
                'message'     =>  '查询失败',
                'data' => $data
            ];
        }
    }

    public function remake_password(Request $request){
        $token = getToken($request);
        $uid =Redis::get("code:".$token);
        $data=$request->only("oldPassword","newPassword");
        $user = DB::table("users")->where("id",$uid)->first();
        if (Hash::check($data['oldPassword'], $user['password'])) {
            $res = DB::table("users")->where("id",$uid)->update(['password'=>Hash::make($data['newPassword'])]);
        }else{
            return ThrowApiExc('102');
        }

        if($res){
            return [
                'status_code'      => 200,
                'message'     =>  '修改成功',
                'data' => $res
            ];
        }else{
            return [
                'status_code'      => 200,
                'message'     =>  '修改失败',
                'data' => $res
            ];
        }
    }

    public function select_phone_user(Request $request){
        
    }

}